# -*- coding: utf-8 -*-
import ctypes
import threading
import time
import tkinter as tk


class MessageBox:
    """跨线程安全的消息框类"""

    @staticmethod
    def info(title: str, message: str, parent=None):
        """使用ctypes显示消息框，避免Tkinter线程问题"""

        def _show_info():
            ctypes.windll.user32.MessageBoxW(0, message, title, 0x40)  # MB_ICONINFORMATION

        if threading.current_thread() == threading.main_thread():
            _show_info()
        else:
            # 在主线程中执行
            if hasattr(MessageBox, '_root'):
                MessageBox._root.after(0, _show_info)
            else:
                # 如果没有Tkinter环境，创建临时环境
                threading.Thread(target=_show_info, daemon=True).start()

    @staticmethod
    def warning(title: str, message: str, parent=None):
        def _show_warning():
            ctypes.windll.user32.MessageBoxW(0, message, title, 0x30)  # MB_ICONWARNING

        if threading.current_thread() == threading.main_thread():
            _show_warning()
        else:
            if hasattr(MessageBox, '_root'):
                MessageBox._root.after(0, _show_warning)
            else:
                threading.Thread(target=_show_warning, daemon=True).start()

    @staticmethod
    def error(title: str, message: str, parent=None):
        def _show_error():
            ctypes.windll.user32.MessageBoxW(0, message, title, 0x10)  # MB_ICONERROR

        if threading.current_thread() == threading.main_thread():
            _show_error()
        else:
            if hasattr(MessageBox, '_root'):
                MessageBox._root.after(0, _show_error)
            else:
                threading.Thread(target=_show_error, daemon=True).start()

    @staticmethod
    def confirm(title: str, message: str, parent=None) -> bool:
        """确认对话框，返回True/False"""
        result = [False]

        def _show_confirm():
            nonlocal result
            response = ctypes.windll.user32.MessageBoxW(0, message, title, 0x24)  # MB_YESNO + MB_ICONQUESTION
            result[0] = (response == 6)  # IDYES = 6

        if threading.current_thread() == threading.main_thread():
            _show_confirm()
        else:
            if hasattr(MessageBox, '_root'):
                MessageBox._root.after(0, _show_confirm)
                # 等待响应
                while not result[0]:
                    MessageBox._root.update()
                    time.sleep(0.01)
            else:
                _show_confirm()

        return result[0]


# 使用示例
if __name__ == "__main__":
    # 创建示例窗口
    root = tk.Tk()
    root.title("消息弹窗示例")
    root.geometry("400x400")

    # 创建按钮框架
    frame = tk.Frame(root)
    frame.pack(expand=True, fill=tk.BOTH, padx=20, pady=20)

    # 添加测试按钮
    tk.Button(frame, text="信息提示",
              command=lambda: MessageBox.info("提示", "这是一个信息提示弹窗！", root)).pack(pady=5)

    tk.Button(frame, text="确认对话框",
              command=lambda: print(f"用户选择了: {MessageBox.confirm('确认', '您确定要执行此操作吗？', root)}")).pack(
        pady=5)

    tk.Button(frame, text="警告消息",
              command=lambda: MessageBox.warning("警告", "这是一个警告消息！", root)).pack(pady=5)

    tk.Button(frame, text="错误消息",
              command=lambda: MessageBox.error("错误", "这是一个错误消息！", root)).pack(pady=5)

    tk.Button(frame, text="输入对话框",
              command=lambda: print(f"用户输入了: {MessageBox.input('输入', '请输入内容:', root)}")).pack(pady=5)

    tk.Button(frame, text="颜色选择",
              command=lambda: print(f"选择的颜色: {MessageBox.color_chooser('选择颜色', root)}")).pack(pady=5)

    tk.Button(frame, text="打开文件",
              command=lambda: print(f"选择的文件: {MessageBox.file_open('打开文件', root)}")).pack(pady=5)

    tk.Button(frame, text="自定义信息弹窗",
              command=lambda: MessageBox.custom_info("自定义提示", "这是一个自定义信息弹窗！", root)).pack(pady=5)

    root.mainloop()